<template>
  <div class="wap-container manCreatedOrder">
    <div class="user-info" v-if="isNewOrder">
      <div>
        <span class="c666 title">
          派单人
        </span>
        <span class="ml10">{{userInfo.nickName}}</span>
      </div>
      <div>
        <span class="c666 title">
          联系电话
        </span>
        <span class="ml10">{{userInfo.mobile}}</span>
      </div>
    </div>
    <section class="top pt5 pr10 pl10 bgfff">
      <div class="mess-item rowflex" v-if="!isNewOrder">
        <div class="c666 title">
          客户姓名
        </div>
        <input id="phone" v-model="form.linkMan" type="text" placeholder="请填写"/>
      </div>
      <div class="mess-item rowflex" v-if="!isNewOrder">
        <div class="c666 title-box">
          <div>电</div>
          <div>话</div>
        </div>
        <input id="name" v-model="form.linkPhone" type="text" placeholder="请填写"/>
      </div>
      <div class="appointTime">
        <datetime-range title="截止时间" placeholder="请选择截止时间" :start-date="_dateFormat(new Date())"
                        :end-date="_dateFormat(new Date(new Date()-(-1000*60*60*24*15)))"
                        v-model="preFinishedTime">
          <div solt="title">截止时间<img src="~assets/images/icon_bitian@2x.png"></div>
        </datetime-range>
      </div>
      <div class="mess-item star rowflex">
        <div class="c666 title">工作代码</div>
        <img src="~assets/images/icon_bitian@2x.png">
        <select v-model="form.workOrderType">
          <option value="placeholder" disabled selected class="hide">请选择工作代码</option>
          <option v-for="option in OUTGDWFLXList" v-bind:value="option">
            {{ option.name }}
          </option>
        </select>
      </div>
      <div class="mess-item star rowflex">
        <div class="c666 title">流程模板</div>
        <img src="~assets/images/icon_bitian@2x.png">
        <select v-model="form.workFlow.id">
          <option value="placeholder" disabled selected class="hide">请选择流程模板</option>
          <option v-for="option in workFlowOptions" v-bind:value="option.id">
            {{ option.workFlowName}}
          </option>
        </select>
      </div>
      <div class="mess-item star rowflex">
        <div class="c666 title-box">
          <div>区</div>
          <div>县</div>
        </div>
        <img src="~assets/images/icon_bitian@2x.png">
        <select  @change="getCustomer" v-model="form.county">
          <!--<option value="placeholder" disabled selected class="hide">请选择区县</option>-->
          <option  v-for="option in countyOptions" v-bind:value="option">
            {{ option }}
          </option>
        </select>
      </div>
      <div class="mess-item star rowflex">
        <div class="c666 title">服务对象</div>
        <img src="~assets/images/icon_bitian@2x.png">
        <select @change="getEquipment" v-model="form.customer.id">
          <option value="placeholder" disabled selected class="hide">请选择服务对象</option>
          <option :selected="option.isSelect" v-for="option in serviceObjectOptions" v-bind:value="option.id">
            {{ option.customerName }}
          </option>
        </select>
      </div>
      <div class="warrantyStatus" v-if="equipmentInfo">
        <span v-if="equipmentInfo.warrantyTime">维保到期日期：{{equipmentInfo.warrantyTime}}</span>
        <span v-if="equipmentInfo.warrantyStatus">维保状态：{{equipmentInfo.warrantyStatus}}</span>
      </div>
      <div class="mess-item  rowflex">
        <div class="c666 title">设备编号</div>
        <select v-model="form.equipment.id" @change="getEquipmentInfo(form.equipment.id)">
          <option value="placeholder" disabled selected class="hide">请选择设备编号</option>
          <option v-for="option in equipmentOptions" v-bind:value="option.id">
            {{ option.equipmentNo }}
          </option>
        </select>
      </div>
      <div class="mess-item rowflex" v-if="false">
        <div class="c666 title">图片上传</div>
        <div class="selectStyle" @click="showPopup"><span>{{picPathList.length}}张图片</span></div>
      </div>
      <div class="mess-item rowflex">
        <div class="c666 title">服务位置</div>
        <div class="selectStyle" @click="choiceLocation()">{{this.wktText}}</div>
      </div>
      <div class="mess-item star rowflex">
        <div class="c666 title">工作内容</div>
        <img src="~assets/images/icon_bitian@2x.png">
        <group :gutter="0" class="textarea">
          <x-textarea :show-counter="true" :max="140" style="width: 2.75rem; padding: 0; margin-left: 0" v-model="form.errorDescription">

          </x-textarea>
        </group>
        <!--<input v-model="form.errorDescription" type="text"  placeholder="请填写"/>-->

      </div>
      <div class="mess-item rowflex">
        <div class="c666 title-box">
          <div>数</div>
          <div>量</div>
        </div>
        <input type="number" placeholder="请填写" v-model="form.num"/>
      </div>
      <div class="mess-item star rowflex">
        <div class="c666 title-box">
          <div>工</div>
          <div>程</div>
          <div>师</div>
        </div>
        <img src="~assets/images/icon_bitian@2x.png">
        <select v-model="form.engineer.id">
          <option value="placeholder" disabled selected class="hide">请选择工程师</option>
          <option v-for="option in engineerOptions" v-bind:value="option.id">
            {{ option.nickName }}
          </option>
        </select>
      </div>
    </section>
    <section class="bottom_bar cfff" @click="createdOrder()">
      确定
    </section>

    <div v-transfer-dom>
      <popup v-model="createPopup" height="100%" style="background-color: #fff">
        <div style="height: 30px;text-align: right;line-height: 20px;margin-right: 5px">
          <span @click="showPopup" style="line-height: 30px;font-size: 15px">完成</span></div>
        <UploadImage :imgs="picPathList"></UploadImage>
      </popup>
    </div>

    <div v-transfer-dom>
      <popup v-model="showMap" height="80%">
        <popup-header
          :left-text="cancel"
          :right-text="done"
          title="选择位置"
          :show-bottom-border="false"
          @on-click-left="cancelMap"
          @on-click-right="sureMap"></popup-header>
        <x-input @on-enter="searchSure" class="weui-vcode" v-model="search" placeholder="输入地址">
          <i slot="label" style="margin-right: 10px" class="fa fa-map-marker"></i>
        </x-input>
        <div id="container" style="height: calc(100% - 82px);width: 100%;"></div>
      </popup>
    </div>
  </div>


</template>

<script>
    import {Group, XInput, XTextarea, Selector, Cell, Icon, XButton, PopupHeader, Popup, TransferDom, Radio, PopupPicker,DatetimeRange, } from 'vux'
    import UploadImage from './uploadImage.vue'
    import AMap from 'AMap'
    import AMapUI from 'AMapUI'
    import icon from "@/assets/images/mark_b.png"
    export default {
      name: "ManCreatedOrder",
      components: {
        Group,
        XInput,
        XTextarea,
        Selector,
        Cell,
        Icon,
        XButton,
        PopupHeader,
        Popup,
        Radio,
        UploadImage,
        PopupPicker,
        DatetimeRange,
      },
      directives: {
        TransferDom
      },
      data() {
        return {
          form: {
            backgrounder: {
              id: ''
            },
            county: '',
            customer: {
              id: ''
            },
            engineer: {
              id: ''
            },
            equipment: {
              id: ''
            },
            errorDescription: '',
            linkMan: '',
            linkPhone: '',
            proposer: {
              id: ''
            },
            repairFileStore: '',
            workOrderType: '',
            preFinishedTime: '',
            workFlow: {
              id: ''
            },
          },
          postForm: {
            backgrounder: {
              id: ''
            },
            county: '',
            customer: {
              id: ''
            },
            engineer: {
              id: ''
            },
            equipment: {
              id: ''
            },
            errorDescription: '',
              linkMan: '',
              linkPhone: '',
              proposer: {
              id: ''
            },
            repairFileStore: '',
            workOrderType: '',
            preFinishedTime: '',
            workFlow: {
              id: ''
            },
          },
          preFinishedTime: [],
          showMap: false,
          search: '',//地址搜索,
          cancel: '取消',
          done: '确定',
          subjectContent: {},
          lnglat: null,
          wktText: '',
          current: '',
          createPopup: false,
          picPathList: [],
          picIdList: [],
          customer: {},
          GDWFLXList: [],
          OUTGDWFLXList: [],
          serviceObject: '',
          county: '',
          workCode: '',
          workCodeOptions: [
            '1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3'
          ],
          workFlowOptions: [],
          countyOptions: [],
          serviceObjectOptions: [],
          equipmentOptions: [],
          engineerOptions: [],
          requestInfo: {},
          equipmentInfo: {},
          userInfo: {},
          isNewOrder: false,
        }
      },
      mounted() {
          this.getRequestInfo()
          console.log(this.requestInfo)
          this.getFWLXList()
          this.getWorkFlow()
          this.getCountys()
          // 工程师名单获取
          this.getGCSList()
      },
      methods: {
        getRequestInfo: function () {
          this.$getUserInfo().then(user=> {
            this.userInfo = user
            this.form.backgrounder.id =  user.id
            if (this.$route.query.requestInfo) {
              this.requestInfo = this.$route.query.requestInfo
              this.workCode = this.requestInfo.workOrderType
              console.log(this.$route.query.requestInfo)
              console.log(1111)
              this.form.linkMan = this.requestInfo.linkMan
              this.form.linkPhone = this.requestInfo.linkPhone
              this.form.workOrderType = this.requestInfo.workOrderType
              this.form.repairFileStore = this.requestInfo.repairFileStore
              this.form.errorDescription = this.requestInfo.errorDescription
              this.form.county = this.requestInfo.county
              if (this.requestInfo.engineer) {
                this.form.engineer = this.requestInfo.engineer
              }

              if (this.requestInfo.customer) {

                this.search = this.requestInfo.customer.address  // 服务网点位置

                //获取区县下的服务对象
                this.$http.get('/work/api/customer/customerOfCountys?county='+ this.form.county).then(res=>{
                  this.serviceObjectOptions = res.data.data
                  this.form.customer.id = this.requestInfo.customer.id
                  this.getEquipment()
                })
              }
              console.log(this.customer)
              if (this.requestInfo.proposer) {
                this.form.proposer.id = this.requestInfo.proposer.id
              } else {
                this.form.proposer = null
              }
              if (this.requestInfo.equipment){
                this.form.equipment.id = this.requestInfo.equipment.id
              } else {
                this.form.equipment.id = ''
              }
            }else {
              this.isNewOrder = true
              this.form.proposer.id = user.id
              this.form.linkMan = user.nickName
              this.form.linkPhone = user.mobile
            }
          })

        },
        getFWLXList: function () {
          this.$http.get('/work/api/workOrderType/?noPage=true').then(res=>{
              this.GDWFLXList = res.data.data
              this.GDWFLXList.forEach(item =>{
                if (item.serviceType == 'OUT') {
                  this.OUTGDWFLXList.push(item)
                }
              })
              console.log(this.OUTGDWFLXList)
            }
          )
        },
        getWorkFlow: function () {
          //流程模板获取
          this.$http.get('/work/api/workFlow',{params:{status:0}}).then(res=>{
            this.workFlowOptions = res.data.data.rows
          })
        },
        getCountys: function () {
          //区县获取
          this.$http.get('/work/api/customer/countys').then(res=>{
            for (var i = 0; i < res.data.data.length; i++) {
              if (res.data.data[i] !=='string' && res.data.data[i].length > 0){
                this.countyOptions.push(res.data.data[i])
              }
            }
          })
        },
        getCustomer: function () {
          //获取区县下的服务对象
          this.$http.get('/work/api/customer/customerOfCountys?county='+ this.form.county).then(res=>{
                this.serviceObjectOptions = res.data.data
          })
        },
        getEquipment: function () {
          //服务对象id获取设备地址
          this.$http.get('/work/api/equipment/'+this.form.customer.id +'/equipments').then(res=>{
            this.equipmentOptions = res.data.data
            this.search = res.data.data[0].customer.address  // 服务网点位置
          })
        },
        getEquipmentInfo: function (id){
          this.$http.get('/work/api/equipment/'+ id +'/?fields=customer&include=false').then(res=>{
            this.equipmentInfo = res.data.data
            console.log(this.equipmentInfo)

          })
        },
        getGCSList: function(){
          //获取工程师
          this.$http.get('/account/api/users?roleCode=GCS&noPage=true').then(res=>{
            console.log(res)
            this.engineerOptions = res.data.data
          })
        },
        // 时间转换
        arrayToDate(arr) {
          if(arr.length == 0 ){
            return null
          }
          return this._dateFormat(arr[0]+' '+arr[1]+':'+arr[2]+':00', 'YYYY-MM-DD hh:mm:ss')
        },
        createdOrder: function () {
          // work/api/workorder?workFlowId=gggggg
          this.postForm = JSON.parse(JSON.stringify(this.form))   //深拷贝
          // 判断是否有截止时间
          if (this.preFinishedTime.length == 0){
            this.$vux.alert.show({
              title: '提示',
              content: '请选择截止时间'
            })
            return false
          } else {
            this.postForm.preFinishedTime = this.arrayToDate(this.preFinishedTime, 'yyyy-mm-dd HH:MM:SS')
          }
          if (this.picPathList.length > 0) {
            for (var i = 0; i < this.picPathList.length; i++) {
              this.picIdList.push(this.picPathList[i].id)
            }
          }

          // if (this.postForm.repairFileStore && this.postForm.repairFileStore.length > 0){
          //   this.postForm.repairFileStore += ";"+this.picIdList.join(';')
          // } else {
          //   this.postForm.repairFileStore += this.picIdList.join(';')
          // }

          // 判断是否有工作代码
          if (this.postForm.workOrderType == ''){
            this.$vux.alert.show({
              title: '提示',
              content: '请选择工作代码'
            })
            return false
          }

          // 判断是否有设备id
          if (this.postForm.equipment.id == ""){
            this.postForm.equipment = null
          }
          // 判断是否有服务对象id
          if (this.postForm.customer.id == ""){
            this.postForm.customer = null
          }
          // 判断是否有区县
          if (this.postForm.county == ""){
            this.postForm.county = null
          }
          // 判断是否选择了工程师
          if (this.postForm.engineer.id == ""){
            this.$vux.alert.show({
              title: '提示',
              content: '请选择工程师'
            })
            return false
          }
          // 判断是否有流程模板
          if (this.postForm.workFlow.id == ""){
            for (var i = 0 ; i < this.OUTGDWFLXList.length; i++){
              if (this.postForm.workOrderType.id == this.OUTGDWFLXList[i].id) {
                this.$vux.alert.show({
                  title: '提示',
                  content: '请选择流程模板'
                })
                return false
              }
            }
          }

          if (this.lnglat) {
            this.postForm.wkt = 'Point('+this.lnglat.lng+' '+ this.lnglat.lat + ')'
          }
          this.$http.post('/work/api/workorder', this.postForm).then(res=>{
            if (this.$route.query.requestInfo) {
              let data = {
                status: 1
              }
              this.$http.put('/work/api/request/' + this.requestInfo.id + '/status', data).then(res => {
              })
            }
            this.$router.push({path: '/management/manOrderHome'})
          })
          console.log(this.postForm)
        },
        showPopup: function () {
          this.createPopup = !this.createPopup
        },
        //取消选择
        cancelMap() {
          this.showMap = !this.showMap;
        },
        // 确定选择
        sureMap() {
          this.showMap = !this.showMap;
          this.wktText = this.search
          this.marker = null
          console.log(this.lnglat)

          // this.subjectContent[this.inputLocation] = this.search;
        },
        //搜索地址---正向地理编码
        searchSure(value) {
          this.geocoder.getLocation(value, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              // result中对应详细地理坐标信息
              this.setMarkerAndCenter(result.geocodes[0].location.lng, result.geocodes[0].location.lat);
              this.lnglat = {
                lng: result.geocodes[0].location.lng,
                lat: result.geocodes[0].location.lat
              }
              console.log(this.lnglat)
            } else {
              this.$vux.toast.show({
                type: "warn",
                text: '未找到相关地址'
              })
            }
          })
        },
        //设置选择位置---逆向地理编码
        setLocation(lng, lat) {
          this.setMarkerAndCenter(lng, lat);
          this.lnglat = {lng: lng, lat: lat}
          this.geocoder.getAddress([lng, lat], (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              // result为对应的地理位置详细信息
              this.search = result.regeocode && result.regeocode.formattedAddress;
            }
          })
        },
        //设置中心点坐标和标记
        setMarkerAndCenter(lng, lat) {
            if (this.marker) {
              this.marker.setPosition([lng, lat]);
            } else {
              this.marker = new AMap.Marker({
                icon: icon,
                position: [lng, lat]
              });
              this.marker.setMap(this.map);
            }
            this.map.setZoomAndCenter(this.map.getZoom() >= 16 ? this.map.getZoom() : this.map.getZoom() + 1, [lng, lat])
        },
        //地图定位
        choiceLocation(value) {
          // this.inputLocation = value || '';
        //  this.search = this.subjectContent[this.inputLocation] || '';
          this.showMap = !this.showMap;
          this.map =  new AMap.Map('container', {
            resizeEnable: true,
            zoom: 15,
          });
          AMap.plugin(['AMap.ToolBar', 'AMap.Driving', 'AMap.Geocoder'], () => {//异步同时加载多个插件
            this.geocoder = new AMap.Geocoder({});
            this.search && this.searchSure(this.search);
          });
          this.map.on('click', (ev) => {
            var lnglat = ev.lnglat;
            this.setLocation(lnglat.lng, lnglat.lat);
          });
        },
      },

    }
</script>

<style lang="less">
  .wap-container {
    font-size: 0.13rem;
  }
  .manCreatedOrder {
    .user-info{
      display: flex;
      justify-content: space-between;
      height: 0.4rem;
      background-color: #fff;
      line-height: 0.4rem;
      padding: 0 0.2rem 0 0.1rem;
      margin-bottom: 0.1rem;
    }
    .top {
      padding-bottom: 0.15rem;
      box-shadow: 0 0 0.04rem 0 #ebebeb;
    }
    .appointTime{
      width: 3.45rem;
      height: 0.23rem;
      line-height: 0.23rem;
      .weui-cell{
        padding: 0;
        margin-top: 0.1rem;
        .vux-cell-primary{
          margin-left: 0.17rem;
          padding-right: 0.2rem;
          background: url("~assets/images2/icon_zuojian@2x.png") no-repeat 2.6rem center;
          background-size: 0.06rem 0.1rem;
          border-radius: 0.02rem;
          border: #dfdfdf 1px solid;
        }
        .weui-cell__ft{
          display: none;
        }
      }
    }
    .mess-item {
      margin-top: 0.1rem;
      /*height: 0.25rem;*/
      line-height: 0.25rem;
      width: 100%;
    }
    .top .mess-item:last-child {
      height: 0.6rem;
    }
    .mess-item img {
      width: 0.07rem;
      margin-right: 0.03rem;
      vertical-align: super;
    }
    .mess-item .title-box {
      width: 0.52rem;
      display: flex;
      justify-content: space-between;
    }
    .mess-item.star{
      input{
        margin-left: 0.04rem;
      }
      select,.selectStyle{
        margin-left: 0.04rem;
      }
    }
    .selectStyle{
      margin-left: 0.18rem;
      -webkit-appearance: none;
      border: 0;
      outline: 0;
      background-color: transparent;
      width: 2.75rem;
      padding-right: 0.2rem;
      font-size: 0.13rem;
      line-height: 0.25rem;
      position: relative;
      z-index: 1;
      background: url("~assets/images2/icon_zuojian@2x.png") no-repeat 2.6rem center;
      background-size: 0.06rem 0.1rem;
      border-radius: 0.02rem;
      border: #dfdfdf 1px solid;
      span{
        float: right;
        font-size: 0.1rem;
      }
    }
    .mess-item .title {
      width: 0.52rem;
    }
    input[type="text"],input[type="number"] {
      width: 2.75rem;
      height: 0.25rem;
      margin-left: 0.18rem;
      border-radius: 0.02rem;
      border: #dfdfdf 1px solid;
    }
    #file{
      margin-left: 0.18rem;
      position: relative;
      top: -0.25rem;
      opacity: 0;
    }
    textarea {
      width: 2.55rem;
      padding-left: 0.1rem;
      border-radius: 0.02rem;
    }
    .weui-textarea{
      font-size: 0.13rem;
    }
    .weui-textarea-counter {
      font-size: 0.1rem;
      padding-right: 0.05rem;
    }
    .vux-x-textarea.weui-cell{
      border-right: #dfdfdf 1px solid;
      border-left: #dfdfdf 1px solid;
    }
    .textarea{
      margin-left: 0.08rem;
      font-size: 0.13rem;
      border-radius: 0.02rem;
      border-top: #dfdfdf 1px solid;
    }
    .warrantyStatus{
      display: flex;
      justify-content: space-between;
      width: 2.75rem;
      margin-left: 0.7rem;
    }
    .bottom {
      border-radius: 0.04rem;
      box-shadow: 0 0.02rem 0.04rem 0 #ebebeb;
    }
    .bottom-title {
      padding-top: 0.08rem;
      height: 0.43rem;
      line-height: 0.35rem;
      font-size: 0.15rem;
      text-align: center;
      border-bottom: solid 1px #ebebeb;
    }
    .repair-type {
      display: flex;
      justify-content: space-around;
      margin-top: 0.12rem;
      font-size: 0.15rem;
    }
    .repair-item {
      display: flex;
    }

    .repair-date {
      padding: 0 0.58rem;
      margin-top: 0.37rem;
      display: flex;
      justify-content: space-between;
    }

    .bottom_bar {
      width: 100%;
      background: #42a3fd;
      line-height: 0.43rem;
      font-size: 0.15rem;
      text-align: center;
    }
    select{
      margin-left: 0.18rem;
      -webkit-appearance: none;
      border: 0;
      outline: 0;
      background-color: transparent;
      width: 2.75rem;
      padding-right: 0.2rem;
      font-size: 0.13rem;
      height: 0.25rem;
      line-height: 0.25rem;
      position: relative;
      z-index: 1;
      background: url("~assets/images2/icon_zuojian@2x.png") no-repeat 2.6rem center;
      background-size: 0.06rem 0.1rem;
      border-radius: 0.02rem;
      border: #dfdfdf 1px solid;
    }
  }
</style>
